package com.world.cat.app.utils.qiniu;

import com.world.cat.model.sys.PrivateFile;
import com.world.cat.service.sys.PrivateFileService;
import com.world.common.enums.HttpResultStatus;
import com.world.common.pojo.Result;
import com.world.common.pojo.ResultResponseWrap;
import com.world.common.util.RegexUtils;
import com.world.common.util.SessionUtil;
import com.world.common.util.SysUtil;
import com.world.common.util.sign.MD5Util;
import com.world.core.ServiceManager;
import com.world.core.exception.WorldValidateException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;


/**
 * Created by gang on 2016/12/9.
 */
public class UploadUtil {
    private static final Logger logger = Logger.getLogger(UploadUtil.class);

    //result 中的data是文件的key 用这个key下载的时候
    public static Result upload(MultipartFile file) {
        ResultResponseWrap<PrivateFile> privateFileResultResponseWrap = uploadPrivateFile(SessionUtil.getUserName(), file);
        if (privateFileResultResponseWrap.isSuccess()) {
            PrivateFile privateFile = privateFileResultResponseWrap.getData();
            return new Result(privateFile.getFileKey(), true);
        } else {
            return new Result(false, privateFileResultResponseWrap.getMsg());
        }
    }

    //根据fileKey,换成绝对路径
    public static String getFullDownLoadUrlByFileKey(String fileKey) {
        if (StringUtils.isNotBlank(fileKey)) {
            return getRelativeDownLoadUrlByFileKey(fileKey);
        }
        return "";
    }

    //根据fileId,换成绝对路径
    public static String getFullDownLoadUrlByFileId(String fileId) {
        if (StringUtils.isNotBlank(fileId)) {
            return getRelativeDownLoadUrlByFileId(fileId);
        }
        return "";
    }

    //根据fileKey,换成相对路径
    public static String getRelativeDownLoadUrlByFileKey(String fileKey) {
        return "file/downLoad?fileKey=" + SysUtil.valueOf(fileKey);
    }

    public static String getRelativeDownLoadUrlByFileId(String fileId) {
        return "file/downLoadById?fileId=" + SysUtil.valueOf(fileId);
    }

    // 先上传七牛,再写本地,再计入数据库
    public static ResultResponseWrap<PrivateFile> uploadPrivateFile(String username, MultipartFile file) {
        ResultResponseWrap<PrivateFile> resultResponseWrap = new ResultResponseWrap<>();
        try {
            if (SysUtil.isEmpty(username)) {
                resultResponseWrap.setCode(HttpResultStatus.PARAM_NULL.getCode());
                resultResponseWrap.setMsg("不存在");
                return resultResponseWrap;
            }
            if (file == null || file.isEmpty()) {
                resultResponseWrap.setCode(HttpResultStatus.PARAM_NULL.getCode());
                resultResponseWrap.setMsg("上传文件为空");
                return resultResponseWrap;
            }

            String fileName = file.getOriginalFilename();
            if (StringUtils.isBlank(fileName)) {
                fileName = MD5Util.md5(UUID.randomUUID().toString());
            } else {
                fileName = RegexUtils.filterFileName(fileName);
            }
            String filePathPrefix = QiniuUtil.getQiniuPathPrefix();
            //文件上传七牛
            ReturnBody returnBody = QiniuUtil.privateBucketFileUploadByByteArr(file.getBytes(), filePathPrefix + fileName);
            //文件存在本地
            QiniuUtil.saveLocalPrivateFile(file, filePathPrefix, fileName);
            //保存文件记录
            PrivateFileService privateFileService = ServiceManager.getService(PrivateFileService.class);
            PrivateFile privateFile = privateFileService.savePrivateFile(username, returnBody, filePathPrefix, fileName);
            resultResponseWrap.setCode(HttpResultStatus.SUCCESS.getCode());
            resultResponseWrap.setMsg(HttpResultStatus.SUCCESS.getMsg());
            resultResponseWrap.setData(privateFile);
            return resultResponseWrap;
        } catch (WorldValidateException e) {
            if (StringUtils.isNotBlank(e.getErrorCode())) {
                resultResponseWrap.setCode(e.getErrorCode());
            } else {
                resultResponseWrap.setCode(HttpResultStatus.FAIL.getCode());
            }
            resultResponseWrap.setMsg(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultResponseWrap.setCode(HttpResultStatus.FAIL.getCode());
            resultResponseWrap.setMsg("网络异常");
        }
        return resultResponseWrap;
    }
}
